from PIL import Image, ImageDraw
import random

# 定义图片大小和背景颜色
image_size = (384, 384)
background_color = 192  # 更淡的灰色

# 创建灰色画布
image = Image.new("L", image_size, background_color)
draw = ImageDraw.Draw(image)

# 定义大矩形的边界和填充
large_rect_size = 128  # 大矩形的边长，约为全图的九分之一
large_rect_left = (image_size[0] - large_rect_size) // 2
large_rect_top = (image_size[1] - large_rect_size) // 2
large_rect_coords = (
    large_rect_left, large_rect_top,
    large_rect_left + large_rect_size, large_rect_top + large_rect_size
)
draw.rectangle(large_rect_coords, outline=0, width=2, fill=255)  # 大矩形白色填充，黑色边框

# 随机生成小矩形，确保它们不重叠
num_small_rects = random.randint(5, 10)
small_rects = []  # 存储已生成的小矩形的坐标，用于重叠检测
min_gap = 5  # 小矩形之间的最小空隙

for _ in range(num_small_rects):
    success = False
    for _ in range(100):  # 尝试最多100次，避免死循环
        # 随机生成小矩形的位置和大小
        small_rect_margin = 10
        small_rect_width = random.randint(10, 20)  # 缩小的小矩形宽度
        small_rect_height = random.randint(10, 20)  # 缩小的小矩形高度
        
        x1 = random.randint(large_rect_coords[0] + small_rect_margin, large_rect_coords[2] - small_rect_width - small_rect_margin)
        y1 = random.randint(large_rect_coords[1] + small_rect_margin, large_rect_coords[3] - small_rect_height - small_rect_margin)
        x2 = x1 + small_rect_width
        y2 = y1 + small_rect_height
        
        # 确保矩形边界宽度在1到3之间
        # 数据库存储中心点，长度，宽度，边界厚度
        border_width = random.randint(1, 3)

        # 检查新生成的小矩形是否与现有矩形重叠
        new_rect = [x1, y1, x2, y2]
        overlap = any(
            not (new_rect[2] + min_gap <= rect[0] or new_rect[0] >= rect[2] + min_gap or
                 new_rect[3] + min_gap <= rect[1] or new_rect[1] >= rect[3] + min_gap)
            for rect in small_rects
        )
        
        # 如果没有重叠，则绘制该小矩形并添加到已生成的矩形列表
        if not overlap:
            draw.rectangle(new_rect, outline=0, width=border_width)  # 黑色边框
            draw.rectangle(
                [x1 + border_width, y1 + border_width, x2 - border_width, y2 - border_width], 
                fill=255  # 白色填充
            )
            small_rects.append(new_rect)
            success = True
            break
    
    # 若在100次尝试内找不到不重叠的位置，跳过该小矩形
    if not success:
        print(f"小矩形 {_ + 1} 生成失败，尝试次数过多")

# 保存图像
image.save("output.pgm")
print("图像已保存为output.pgm")
